<?php
require_once '../../../config/common_config.php';
require_once PATH_ROOT.'/inc/global.php';
require_once('.config.inc.php');
$db = createMysqlDbLink($mysql_config["of"]);
echo "work!";
function decodeUnicode($str)
{   
    return preg_replace_callback('/\\\\u([0-9a-f]{4})/i',
        create_function(
            '$matches',
            'return mb_convert_encoding(pack("H*", $matches[1]), "UTF-8", "UCS-2BE");'
        ),
        $str);
}

function changestr($str){
	$t=array();
	preg_match_all('/u([0-9a-f]{4})/',$str,$s);
	foreach($s[0] as $sd){
		$t[]='\\\\'.$sd;
	}
	$l=replaceCode($str,'/u([0-9a-f]{4})/',0);
	for($i=0;$i<count($t);$i++){
		$l=preg_replace("/\[\[$i\]\]/",$t[$i],$l);
	}
	return decodeUnicode($l);

}

function replaceCode($code,$replace,$i=0){
	$codeNew=preg_replace($replace,"[[$i]]",$code,1);
	$i++;
	if($codeNew==$code) return $codeNew;
	else return replaceCode($codeNew,$replace,$i);
}

$count=$db->getValue("select count(*) from `amorderlist` where `ostat`=1 limit 1");   //获取未执行任务个数
echo $count;
if($count>0){   //未执行任务数大于0
	

	$sqlq="select distinct `key` from `amorderlist` where `ostat`=1";
	$queryq=$db->query($sqlq);
	while($arrq=$db->fetchrow($queryq)){
		$key=trim($arrq['key']); echo $key;


	$rand=rand(0,1);
	if($rand==0) $orderby="asc";
	else $orderby="desc";
	//$sql="select * from `amorderlist` where `ostat`=1 limit 1";
	$sql="select * from `amorderlist` where `ostat`=1 and `key` like '".$key."' order by id $orderby limit 5"; echo $sql;
	$query=$db->query($sql);
	while($arr=$db->fetchrow($query)){
	//if(stripos($arr['detail'],"legging")){$fpxtype='A7';}else{$fpxtype='A6';}
	
	$author=$db->getValue("select `author` from `auth` where `source` like 'amazon' and `account` like '".$key."'");
	$auth=json_decode($author,true); 
	/*
	define('AWS_ACCESS_KEY_ID', $auth['AWS_ACCESS_KEY_ID']);
    define('AWS_SECRET_ACCESS_KEY', $auth['AWS_SECRET_ACCESS_KEY']);
	define ('MERCHANT_ID', $auth['MERCHANT_ID']);
    define ('MARKETPLACE_ID', $auth['MARKETPLACE_ID']);
	*/
	if($auth['MARKETPLACE_ID']=='ATVPDKIKX0DER') $serviceUrl = "https://mws.amazonservices.com/Orders/2013-09-01";
	if($auth['MARKETPLACE_ID']=='A1VC38T7YXB528') $serviceUrl="https://mws.amazonservices.jp/Orders/2013-09-01";
	if(in_array($auth['MARKETPLACE_ID'],array('A1F83G8C2ARO7P','A1PA6795UKMFR9','A1RKKUPIHCS9HS','A13V1IB3VIYZZH','APJ6JRA9NG5V4')))$serviceUrl=$serviceUrl_eu;
	$config = array (
   'ServiceURL' => $serviceUrl,
   'ProxyHost' => null,
   'ProxyPort' => -1,
   'ProxyUsername' => null,
   'ProxyPassword' => null,
   'MaxErrorRetry' => 3,
 );

 $service = new MarketplaceWebServiceOrders_Client(
        $auth['AWS_ACCESS_KEY_ID'],
        $auth['AWS_SECRET_ACCESS_KEY'],
        APPLICATION_NAME,
        APPLICATION_VERSION,
        $config);
$message="";
	$order=json_decode($arr['detail'],true);//echo $arr['detail'];
	print_r($order);
	if(!$order||$order==array()){
		$db->query("update `amorderlist` set `ostat`=2 where `ordernum` like '".$arr['ordernum']."'");
		//die();
	}
	$type = ($order['FulfillmentChannel']=="MFN")?"1":"2";
	$stat = $arr['stat'];
	$comefrom = $arr['comefrom']; 
	$request = new MarketplaceWebServiceOrders_Model_ListOrderItemsRequest();
	$request->setSellerId($auth['MERCHANT_ID']);
	$request->setAmazonOrderId($order['AmazonOrderId']); //print_r($request);
	$order['detail']=invokeListOrderItems($service, $request);print_r($order['detail']);
	
	$ordernum = $order['AmazonOrderId'];
	$shipping_add	= changestr($order['ShippingAddress']['Name'])."<br>".changestr($order['ShippingAddress']['AddressLine1'])." ".changestr($order['ShippingAddress']['AddressLine2'])." ".changestr($order['ShippingAddress']['AddressLine3'])."<br>".changestr($order['ShippingAddress']['City']).",".changestr($order['ShippingAddress']['StateOrRegion']).",".$order['ShippingAddress']['CountryCode']."<br>".changestr($order['ShippingAddress']['PostalCode'])."<br>".$order['ShippingAddress']['Phone'];
	if($order['detail']==false){
		$db->query("update `amorderlist` set `ostat`=2 where `ordernum` like '$ordernum'");
	}else{
		$details=array();
		$skus=array();
	if(is_array($order['detail'][0])){ echo "more items<br>";
		foreach($order['detail'] as $os){
			if($order['ShippingAddress']['CountryCode']=='GB'||$order['ShippingAddress']['CountryCode']=='IM'||$order['ShippingAddress']['CountryCode']=='JE'){
				$countrycode="UK";
			}elseif($order['ShippingAddress']['CountryCode']=='MH'){
				$countrycode="US";
			}else{
				$countrycode=($order['ShippingAddress']['CountryCode'])?$order['ShippingAddress']['CountryCode']:"US";
			}
			
			//$realkey=substr($key,0,strlen($key)-2).$countrycode; 
			
			if($countrycode=="PR"||$countrycode=="VI"||$countrycode=="GU"||$countrycode=="MP") $realkey=substr($key,0,strlen($key)-2)."US";//波多黎各
			$realkey=$key;
			$asin=$os['ASIN'];
			$skus[] = str_replace("'","-",$os['SellerSKU']);
			$picture="<img width=\"150px\" height=\"150px\" src=\"../img/".get_pic(str_replace("'","-",$os['SellerSKU']))."\" />";
			$qc=($os['QuantityOrdered']==1)?"":"style=\"color:red\"";
			$details[]	= "<table border=\"1px\" class=\"detail_talbe\" bordercolor=\"#666666\"><tr><td rowspan=\"4\">".$picture."</td><td colspan=\"2\">".addslashes($os['Title'])."</td></tr><tr><td ".$qc.">Quantity:</td><td ".$qc.">".$os['QuantityOrdered']."</td></tr><tr><td>SKU:</td><td>".str_replace("'","-",$os['SellerSKU'])."</td></tr><tr><td>Order-Item ID:</td><td>".$os['OrderItemId']."</td></tr></table>";
			$is_gotsku=$db->getValue("select count(*) from `skulist` where `oldsku` like '".str_replace("'","-",$os['SellerSKU'])."'");
			if($is_gotsku==0||!is_file("../../img/".get_pic(str_replace("'","-",$os['SellerSKU'])))){
			$getpic=new MarketplaceWebServiceOrders_amapi_apiclass;echo $asin." ----- ".$realkey."-----".str_replace("'","-",$os['SellerSKU'])."<br>";
			echo $getpic->downloadPicFromAsin($asin,$realkey,get_pic(str_replace("'","-",$os['SellerSKU'])));
			}
		}
		$sku=implode("<br>",$skus);
		$detail=implode("<br>",$details);
		
	}else{ echo "single item<br>";
		if($order['ShippingAddress']['CountryCode']=='GB'||$order['ShippingAddress']['CountryCode']=='IM'||$order['ShippingAddress']['CountryCode']=='JE'){
				$countrycode="UK";
			}elseif($order['ShippingAddress']['CountryCode']=='MH'||$order['ShippingAddress']['CountryCode']=='FM'){
				$countrycode="US";
			}else{
				$countrycode=($order['ShippingAddress']['CountryCode'])?$order['ShippingAddress']['CountryCode']:"US";
			}
		//$realkey=substr($key,0,strlen($key)-2).$countrycode;
		
		if($countrycode=="PR"||$countrycode=="VI"||$countrycode=="GU"||$countrycode=="MP") $realkey=substr($key,0,strlen($key)-2)."US";//波多黎各
		$realkey=$key;

		$asin=$order['detail']['ASIN'];
	$sku  		= str_replace("'","-",$order['detail']['SellerSKU']);
	$picture="<img width=\"150px\" height=\"150px\" src=\"../img/".get_pic($sku)."\" />";
	$qc=($order['detail']['QuantityOrdered']==1)?"":"style=\"color:red\"";
	$detail		= "<table border=\"1px\" class=\"detail_talbe\" bordercolor=\"#666666\"><tr><td rowspan=\"4\">".$picture."</td><td colspan=\"2\">".addslashes($order['detail']['Title'])."</td></tr><tr><td ".$qc.">Quantity:</td><td ".$qc.">".$order['detail']['QuantityOrdered']."</td></tr><tr><td>SKU:</td><td>".$sku."</td></tr><tr><td>Order-Item ID:</td><td>".$order['detail']['OrderItemId']."</td></tr></table>";
	$is_gotsku=$db->getValue("select count(*) from `skulist` where `oldsku` like '".$sku."'"); //echo $detail;
	if($is_gotsku==0||!is_file("../../img/".get_pic(str_replace("'","-",$os['SellerSKU'])))){
	$getpic=new MarketplaceWebServiceOrders_amapi_apiclass;echo $asin." ----- ".$realkey."-----".$sku."<br>";
	echo $getpic->downloadPicFromAsin($asin,$realkey,get_pic($sku));
	}
	
	}
	$addtime	   	= date("Y-m-d H:i:s",time());
	$paymentdate		= date("Y-m-d H:i:s",strtotime($order['PurchaseDate']));
	$trackid		= "";

if(($type=="")||($comefrom=="")||($ordernum=="")||($shipping_add=="")||($detail=="")||($stat=="")||($addtime==""))
{
	$message.= "信息不完整，一分钟后重新执行本任务。。";echo $message;
	//echo "<script>	function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',60000);</script>";
}
$is_dup=$db->getValue("select count(*) from `orders` where `ordernum`='$ordernum'");    //查询该订单是否已经录入
if($is_dup>0){   //录入过的订单更新状态
	echo "this is old order<br>";
	$sql = "update `orders` set `types`='$type' ,`comefrom`='$comefrom' ,`ordernum`='$ordernum' ,`sku`='$sku',`shipping_add`='$shipping_add' ,`detail`='$detail' , `stat`='$stat',`adddt`='$addtime' ,`paymentdate`='$paymentdate' where `ordernum` like '$ordernum'";
	//echo $sql;
	$flag=$db->query($sql);
		if($flag){ echo "order update success<br>";
				$order_id=$db->getvalue("select id from `orders` where `ordernum`='$ordernum' ");
				$memo1="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:修改订单。";
				$sqlx = "insert into `order_info` (`order_id`,`action`)values($order_id,'$memo1')";
				$db->query($sqlx);
				$feedetail=array();
				if(is_array($order['detail'][0])){ //一单多件
					$pris=array();
					foreach($order['detail'] as $os){
					$price = $os['ItemPrice'];
					if($price['CurrencyCode']=='USD') //$pris[]="$".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					$pris[]="$".$price['Amount'];
					if($price['CurrencyCode']=='GBP') //$pris[]="£".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					$pris[]="£".$price['Amount'];
					if($price['CurrencyCode']=='EUR') //$pris[]="€".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					$pris[]="€".$price['Amount'];
					if($price['CurrencyCode']=='JPY')
					$pris[]="JP￥".$price['Amount'];
					if($price['CurrencyCode']=='CAD')
					$pris[]="CA$".$price['Amount'];

					updatequantity($ordernum,str_replace("'","-",$os['SellerSKU']),$os['QuantityOrdered']);
					$feedetail[]=$price['Amount']."+".$os['ShippingPrice']['Amount'];
					}
					$pri=implode(",",$pris);
					$feed="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:运费详情:<br>".implode("<br>",$feedetail);
					$db->query("insert into `order_info` (`order_id`,`action`)values($order_id,'$feed')");
					
					$db->query("update `order_price` set `oid`=$order_id,`price`='$pri' where `oid` like '$order_id'");

				}else{  //一单一件
					$price = $order['detail']['ItemPrice'];
					if($price['CurrencyCode']=='USD') //$pri="$".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					$pri="$".$price['Amount'];
					if($price['CurrencyCode']=='GBP') //$pri="£".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					$pri="£".$price['Amount'];
					if($price['CurrencyCode']=='EUR') //$pri="€".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					$pri="€".$price['Amount'];
					if($price['CurrencyCode']=='JPY')
					$pri="JP￥".$price['Amount'];
					if($price['CurrencyCode']=='CAD')
					$pri="CA$".$price['Amount'];
					$feedetail[]=$price['Amount']."+".$order['detail']['ShippingPrice']['Amount'];
					//echo "update `order_price` set `oid`=$order_id,`price`='$pri' where `oid` like '$order_id'";
					$db->query("update `order_price` set `oid`=$order_id,`price`='$pri' where `oid` like '$order_id'");
					$feed="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:运费详情:<br>".implode("<br>",$feedetail);
					$db->query("insert into `order_info` (`order_id`,`action`)values($order_id,'$feed')");

					updatequantity($ordernum,str_replace("'","-",$order['detail']['SellerSKU']),$order['detail']['QuantityOrdered']);

				}
			$message.= $ordernum." update success!...";
			$db->query("update `amorderlist` set `ostat`=0 where `ordernum` like '$ordernum'");
		}else{
			echo "order update failure<br>";
			$message.= $ordernum." update failure!...";
		}
$m=date("Y-m-d h:i:s",time())."\n";
$m.=$message."\n";
$m.="----------------------------------------\n";
$files=fopen("amod.log","a+");
fwrite($files,$m);
fclose($files);
echo $m;
}else{     //新订单录入
	echo "this is new order <br>";
	$sql = "INSERT INTO  `orders` (`types` ,`comefrom` ,`ordernum` ,`sku`,`shipping_add` ,`detail` ,`stat` ,`adddt` ,`paymentdate`,`trackid`)VALUES (  '$type',  '$comefrom',  '$ordernum', '$sku', '$shipping_add',  '$detail',  '$stat',  '$addtime', '$paymentdate', '$trackid')";
	$flag=$db->query($sql);
	
		if($flag){
			echo "order insert success <br>";
				$order_id=$db->getvalue("select max(id) from `orders`");
				$memo1="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:提交订单。";
				$sqlx = "insert into `order_info` (`order_id`,`action`)values($order_id,'$memo1')";
				$db->query($sqlx);
				$feedetail=array();

				if(is_array($order['detail'][0])){
					$pris=array();
					foreach($order['detail'] as $os){
					$price = $os['ItemPrice'];
					if($price['CurrencyCode']=='USD') $pris[]="$".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pris[]="£".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pris[]="€".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='JPY')
					$pris[]="JP￥".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					$feedetail[]=$price['Amount']."+".$os['ShippingPrice']['Amount'];
					updatequantity($ordernum,str_replace("'","-",$os['SellerSKU']),$os['QuantityOrdered']);
					
					}
					$pri=implode(",",$pris);
					$feed="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:运费详情:<br>".implode("<br>",$feedetail);
					$db->query("insert into `order_info` (`order_id`,`action`)values($order_id,'$feed')");
					$db->query("insert into `order_price` (`oid`,`price`)values($order_id,'$pri')");
				}else{
				$price = $order['detail']['ItemPrice'];
				$pri="";
				if($price['CurrencyCode']=='USD') $pri="$".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='GBP') $pri="£".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='EUR') $pri="€".($price['Amount']+$order['detail']['ShippingPrice']['Amount']+$order['detail']['GiftWrapPrice']['Amount']+$order['detail']['ItemTax']['Amount']+$order['detail']['ShippingTax']['Amount']+$order['detail']['GiftWrapTax']['Amount']-$order['detail']['ShippingDiscount']['Amount']);
					if($price['CurrencyCode']=='JPY')
					$pri="JP￥".($price['Amount']+$os['ShippingPrice']['Amount']+$os['GiftWrapPrice']['Amount']+$os['ItemTax']['Amount']+$os['ShippingTax']['Amount']+$os['GiftWrapTax']['Amount']-$os['ShippingDiscount']['Amount']);
					$feedetail[]=$price['Amount']."+".$order['detail']['ShippingPrice']['Amount'];
					$db->query("insert into `order_price` (`oid`,`price`)values($order_id,'$pri')");
					updatequantity($ordernum,str_replace("'","-",$order['detail']['SellerSKU']),$order['detail']['QuantityOrdered']);
					$feed="操作者:SYSTEM <br>操作时间:".$addtime."<br>操作备注:运费详情:<br>".implode("<br>",$feedetail);
					$db->query("insert into `order_info` (`order_id`,`action`)values($order_id,'$feed')");
				}
				$db->query("update `amorderlist` set `ostat`=0 where `ordernum` like '$ordernum'");
			$message.= $ordernum." insert success!...";

			
		}else{
			echo "order insert failure<br>";
			$message.= $ordernum." insert failure!...";
		}

$m=date("Y-m-d h:i:s",time())."\n";
$m.=$message."\n";
$m.="----------------------------------------\n";
$files=fopen("amod.log","a+");
fwrite($files,$m);
fclose($files);
echo $m;
}
	}
	}

	}

$db->close();

//echo "<script>function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',3000);</script>";    //完成一个任务等3秒执行下一个任务
}else{   //没有未执行任务
	$message.= "Mission Complete!\n";
	echo $message;
	//echo "<script>window.location.href='http://www.haixing001.com/admin/MarketplaceWebServiceOrders/amapi/GetOrderList.php'</script>";
	exit;
}

function invokeListOrderItems(MarketplaceWebServiceOrders_Interface $service, $request)
  {
      try {
        $response = $service->ListOrderItems($request);

        //echo ("Service Response\n");
        //echo ("=============================================================================\n");

        $dom = new DOMDocument();
        $dom->loadXML($response->toXML());
        $dom->preserveWhiteSpace = false;
        $dom->formatOutput = true;
		$od=$dom->saveXML();
		$xml = simplexml_load_string($od);
		$data1 = json_decode(json_encode($xml),TRUE);
		return $data1['ListOrderItemsResult']['OrderItems']['OrderItem'];
        //echo $dom->saveXML();
        //echo("ResponseHeaderMetadata: " . $response->getResponseHeaderMetadata() . "\n");

     } catch (MarketplaceWebServiceOrders_Exception $ex) {
        $message.="Caught Exception: " . $ex->getMessage() . "\n";
        echo("Response Status Code: " . $ex->getStatusCode() . "\n");
        echo("Error Code: " . $ex->getErrorCode() . "\n");
        echo("Error Type: " . $ex->getErrorType() . "\n");
        echo("Request ID: " . $ex->getRequestId() . "\n");
        //echo("XML: " . $ex->getXML() . "\n");
        //echo("ResponseHeaderMetadata: " . $ex->getResponseHeaderMetadata() . "\n");
		//echo("<h1>发现错误，3秒后重试。。</h1>");
		//echo "<script>function refreshPage() { window.location.reload(); } window.setTimeout('refreshPage()',3000);</script>";
		return false;
     }
 }

 function updatequantity($ordernum,$sku,$quantity){
	 global $db;
	 $is_has=$db->getValue("select count(*) from `quantity` where `ordernum` like '$ordernum' and `sku` like '$sku'");
	 if($is_has==0){
		$flag=$db->query("insert into `quantity` (`ordernum`,`sku`,`quantity`)values('$ordernum','$sku','$quantity')");
	 }else{
		$flag=$db->query("update `quantity` set `quantity`='$quantity' where `ordernum` like '$ordernum' and `sku` like '$sku'");
	 }
	 if($flag)$message.= "update quantity success<br>";
	 else $message.= "update quantity failture<br>";
	 return $flag;
 }